package com.hb.gp.impl;

import java.util.List;
import java.util.Map;

import com.hb.gp.GPInsCommand;
import com.hb.gp.GPType;
import com.hb.gp.IGPCommandMessageService;
import com.hb.gp.util.tools.DES;
import com.hb.gp.util.tools.GP_GetMac;
import com.hb.gp.util.tools.GP_Tools;

/**
 * 
 * @author shangzk
 *
 */
@GPType(INS = GPInsCommand.INS_E2)
public class GPStore implements IGPCommandMessageService {
	@Override
	public String makeApduMap(String apdu, Map<String, Object> map) {
		if (apdu.startsWith("80E2"))
			return gp80E2(apdu, map);
		else
			return cmd04E2(apdu, map);
	}

	@SuppressWarnings("unchecked")
	private String gp80E2(String apdu, Map<String, Object> map) {
		List<String> sessionKey = (List<String>) map
				.get(IGPCommandMessageService.KEY_SESSION);
		String lastMac = (String) map
				.get(IGPCommandMessageService.VARIBLE_LASTMAC);
		//
		int beginIndex = apdu.indexOf("(") + 1;
		int endIndex = apdu.indexOf(")");
		// TODO Auto-generated method stub
		String sendApdu = "";
		String index = "";
		String d = "";
		String[] data = apdu.substring(beginIndex, endIndex).split(",");
		if (apdu.contains("desEnc")) {
			beginIndex = apdu.indexOf("desEnc");
			sendApdu = apdu.substring(beginIndex);
			beginIndex = sendApdu.indexOf("(") + 1;
			endIndex = sendApdu.indexOf(")");
			String[] descs = sendApdu.substring(beginIndex, endIndex)
					.split(",");
			String desc = DES.encryptTDES_ECB(sessionKey.get(2), descs[0]);
			index = data[2] + data[1];
			desc = GP_Tools.getHexLength(desc) + desc;
			d = GP_Tools.getHexLength(data[0] + desc) + data[0] + desc;
		} else {
			index = data[1] + data[0];
			d = GP_Tools.getHexLength(data[2]) + data[2];
		}
		sendApdu = "84E2" + index + d;
		sendApdu = GP_Tools.getApduMac(sendApdu, sessionKey.get(1), lastMac);
		// 写入mac
		map.put(IGPCommandMessageService.VARIBLE_LASTMAC,
				sendApdu.substring(sendApdu.length() - 16));
		return sendApdu;
	}

	private String cmd04E2(String apdu, Map<String, Object> map) {
		// KEY_ORG_1A, "62B51A2AF059354337AFC4E99E5B0C57"
		// KEY_REC_1A, "D4B7577604ADB28DB4B144D3D99CCCDF"
		String orgKey = "62B51A2AF059354337AFC4E99E5B0C57";
		String newKey = "D4B7577604ADB28DB4B144D3D99CCCDF";
		String encKey = DES.encryptTDES_ECB(orgKey, newKey);
		String atc = "00";
		int beginIndex = apdu.indexOf("(") + 1;
		int endIndex = apdu.indexOf(")");
		String[] params = apdu.substring(beginIndex, endIndex).split(",");
		String cmd = String.format("04E200%s%2x%s%s", params[0],
				((params[2].length() / 2) + 20), encKey, params[2]);
		String mac = GP_GetMac
				.getIMac(cmd, orgKey, "000000000000" + atc, false);
		return cmd + mac.substring(0, 8);
	}

	@Override
	public String makeApduMap(String apdu, Map<String, Object> varibleMap,
			Map<String, Object> storeMap) {
		// TODO Auto-generated method stub
		return apdu;
	}

}
